import storage from '@/utils/storage'
import { createRouter, createWebHashHistory } from 'vue-router'

import NProgress from 'nprogress'

const modules = import.meta.glob(`@/views/**/**.vue`, { eager: true })
const moduleMap = {}

Object.keys(modules).forEach((path) => {
  const module = modules[path]
  path = path.substring(path.indexOf('/views') + 6)
  moduleMap[path] = module

  if (path.endsWith('index.vue')) {
    path = path.substring(0, path.length - 10)
    if (path) {
      moduleMap[path] = module
    }
  }
})

export const routes = [
  {
    path: '/',
    name: '二级路由',
    component: () => import('@/layout/index'),
    redirect: '/index',
    meta: {
      searchable: false,
    },
    children: [
      {
        name: 'index',
        path: '/index',
        component: () => import('@/views/index'),
      },
      {
        name: '403',
        path: '/403',
        component: () => import('@/views/error/403'),
        meta: {
          searchable: false,
        },
      },
      {
        name: '404',
        path: '/404',
        component: () => import('@/views/error/404'),
        meta: {
          searchable: false,
        },
      },
      {
        name: '错误日志',
        path: '/errorLog',
        component: () => import('@/views/error/errorLog'),
      },
    ],
  },
  {
    name: '没有找到',
    path: '/:pathMatch(.*)',
    redirect: '/404',
    meta: {
      searchable: false,
    },
  },
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: routes,
  strict: true,
})

NProgress.configure({ showSpinner: false })

// 加载路由守卫
router.beforeEach(async (to, from, next) => {
  if (!NProgress.isStarted()) {
    NProgress.start()
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

// 加载路由
export function loadDynamicRoutes(menus) {
  let addRoute = (menu) => {
    if (!menu.menuPage || menu.menuType == 'AUTHORITY') {
      return
    }

    router.addRoute('二级路由', {
      name: menu.menuName,
      path: menu.index ? '/index' : menu.menuPage,
      component: () =>
        moduleMap[menu.menuPage] == null
          ? import('@/views/error/404')
          : new Promise((resolve) => {
              resolve(moduleMap[menu.menuPage])
            }),
      meta: {
        title: menu.menuName,
        show: true,
        keepAlive: menu.keepAlive,
        icon: menu.menuIcon,
      },
    })
  }

  for (let i in menus) {
    let menu = menus[i]
    if (menu.menuType == 'CATALOG') {
      for (let j in menu.children) {
        let child = menu.children[j]
        addRoute(child)
      }
    } else if (menu.menuType == 'MENU') {
      addRoute(menu)
    }
  }
}

const menus = storage.get('menus')
if (menus && menus.length > 0) {
  loadDynamicRoutes(menus)
}

export default router
